'use strict';

const conn = require('../../libs/Conn');
const util = require('../../libs/Utils');
const moment = require('moment');

module.exports = async function (params) {

    let engineering_id = util.uuid();
    let engineering_no = '';
    let nowYear = moment().format('YYYY');
    let dataBaseYearSql = `SELECT engineering_no FROM engineering_file ORDER BY engineering_no DESC LIMIT 1`;
    let dataBaseYear = await conn(dataBaseYearSql);
    let year;
    if(dataBaseYear.length>0){
        year = dataBaseYear[0].engineering_no.substring(0,4);
        if(year===nowYear){
            engineering_no =  parseInt(dataBaseYear[0].engineering_no)+1
        }else{
            engineering_no =  nowYear+'00001'
        }
    }else{
        engineering_no =  nowYear+'00001'
    }
    let regionSql = ``;

    let progressSql = `INSERT INTO engineering_progress_file (engineering_id,progress_id) VALUES ('${engineering_id}','${util.uuid()}');INSERT INTO engineering_progress_completion (engineering_id,information_id) VALUES ('${engineering_id}','${util.uuid()}');INSERT INTO engineering_progress_filing (engineering_id) VALUES ('${engineering_id}');`;
    let progressOtherSql = `INSERT INTO engineering_progress_other_data (engineering_id) VALUES ('${engineering_id}');`;
    let insertObj = {
        engineering_id:engineering_id,
        engineering_name:params.eng_name,
        engineering_no:engineering_no,
        startDate:params.eng_startDate,
        structure_id:params.eng_structure_type,
        building_id:params.eng_building_use,
        region_id:params.eng_region_name,
        status:params.eng_status,
    };
    let informationObj = {
        engineering_id:engineering_id,
    };
    let certificateSql = ``;
    for(let i = 1; i<7;i++){
        certificateSql += `INSERT INTO certificate_file (engineering_id,certificate_type,unit_type) VALUES ('${engineering_id}', '${1}','${i}');`
    }
    for(let i = 1; i<7;i++){
        certificateSql += `INSERT INTO certificate_file (engineering_id,certificate_type,unit_type) VALUES ('${engineering_id}', '${2}','${i}');`
    }
    let sql = 'INSERT INTO engineering_file SET ?;INSERT INTO engineering_information_file SET ?;INSERT INTO quality_file SET ? ;'+certificateSql + regionSql+progressSql+progressOtherSql;
    await conn(sql, [insertObj,informationObj,informationObj]);
    return {success: true};
    };